<template>
  <el-card shadow="hover">
    <el-form inline>
      <el-form-item>
        <el-input placeholder="角色名称" v-model="roleName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getRoleList">
          搜索
        </el-button>
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      @click="showAddOrUpdateRole()"
      v-permission="'btn.Role.add'"
    >
      添加
    </el-button>
    <el-button
      type="danger"
      :disabled="!selectedRoleList.length"
      @click="batchRemoveRoleList"
      v-permission="'btn.Role.remove'"
    >
      批量删除
    </el-button>

    <el-table
      :data="roleList"
      border
      class="mt-20"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60"></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
      <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button
            type="info"
            size="small"
            :icon="InfoFilled"
            @click="
              $router.push({
                name: 'RoleAuth',
                query: {
                  id: row.id,
                  roleName: row.roleName,
                },
              })
            "
            v-permission="'btn.Role.assgin'"
          ></el-button>
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="showAddOrUpdateRole(row)"
            v-permission="'btn.Role.update'"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="removeRole(row.id)"
            v-permission="'btn.Role.remove'"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-20"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getRoleList"
      @current-change="getRoleList"
    />

    <el-dialog
      v-model="addOrUpdateRoleDialogVisible"
      :title="`${roleFormData.id ? '更新' : '添加'}角色`"
    >
      <el-form
        label-width="80px"
        ref="roleFormRef"
        :model="roleFormData"
        :rules="roleFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            placeholder="请输入角色名称"
            v-model="roleFormData.roleName"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addOrUpdateRoleDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="addOrUpdateRole"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { Search, InfoFilled, Edit, Delete } from "@element-plus/icons-vue";
import {
  getRoleListApi,
  removeRoleApi,
  batchRemoveRoleListApi,
  addRoleApi,
  updateRoleApi,
} from "@/api/acl/role";
import type { RoleList, RoleItem } from "@/api/acl/models/roleModels";

defineOptions({
  name: "Role",
});

// 5. 批量删除
const selectedRoleList = ref<RoleList>([]);
const handleSelectionChange = (rows: RoleList) => {
  selectedRoleList.value = rows;
};

const batchRemoveRoleList = async () => {
  const idList = selectedRoleList.value.map((role) => role.id as string);
  await batchRemoveRoleListApi(idList);
  ElMessage.success("批量删除角色成功");
  getRoleList();
  selectedRoleList.value = [];
};

// 4. 单个删除
const removeRole = async (id: string) => {
  await removeRoleApi(id);
  ElMessage.success("删除角色成功");
  getRoleList();
};

// 3. 添加或更新用户
const addOrUpdateRoleDialogVisible = ref(false);

const showAddOrUpdateRole = (row: RoleItem = { id: "", roleName: "" }) => {
  addOrUpdateRoleDialogVisible.value = true;
  roleFormData.roleName = row.roleName;
  roleFormData.id = row.id;
  roleFormRef.value?.clearValidate();
};

const roleFormRef = ref();

const roleFormData = reactive<RoleItem>({
  id: "",
  roleName: "",
});

const roleFormRules = reactive({
  roleName: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur",
    },
  ],
});

const addOrUpdateRole = async () => {
  await roleFormRef.value.validate();

  const id = roleFormData.id;

  if (id) {
    await updateRoleApi(roleFormData.id, roleFormData.roleName);
  } else {
    await addRoleApi(roleFormData.roleName);
  }

  ElMessage.success(`${id ? "更新" : "添加"}角色成功`);
  getRoleList();
  addOrUpdateRoleDialogVisible.value = false;
};

// 2. 搜索&清空功能
const roleName = ref("");

const reset = () => {
  roleName.value = "";
  getRoleList();
};

// 1. 获取角色列表展示
const roleList = ref<RoleList>([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const loading = ref(false);

const getRoleList = async () => {
  loading.value = true;
  const res = await getRoleListApi({
    page: currentPage.value,
    limit: pageSize.value,
    roleName: roleName.value,
  });
  roleList.value = res.items;
  total.value = res.total;
  loading.value = false;
};

onMounted(getRoleList);
</script>

<style scoped lang="scss"></style>
